package biz.datalk.industrialland.common.component.interceptor;

import biz.datalk.industrialland.common.annotation.IgnoreToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * {@link IgnoreToken} 注解使用
 * 跳过登录验证
 *
 * @author       tarofang@163.com
 * @date         2019-08-19
 */
@Slf4j
public class DatalkAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.debug("{}:{}", request.getMethod(), request.getRequestURL());

        if (handler instanceof HandlerMethod && !request.getMethod().equals(HttpMethod.OPTIONS.name())) {
            HandlerMethod methodHandler = (HandlerMethod) handler;
            Object bean = methodHandler.getBean();
            Class<?> type = bean.getClass();
            // methodHandler.hasMethodAnnotation(IgnoreToken.class);
            // type.isAnnotationPresent(IgnoreToken.class);
            if (type.getAnnotation(IgnoreToken.class) != null || methodHandler.getMethodAnnotation(IgnoreToken.class) != null) {
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
